const http = require('http');
const fs = require('fs');
const url = require('url');
const path = require('path');
const ws = require('nodejs-websocket');


// * HTTP服务器 start ************************************************** //
// 服务器端口
const httpPort = 8080;
// 自定义HTTP根目录
const root = path.join(__dirname, '../public/');

let httpServer = http.createServer((request, response) => {

    // 获取URL请求路径
    let pathName = url.parse(request.url).pathname;
    // 定位服务器文件路径
    let filePath = path.join(root, pathName);
    // 获取文件状态
    if (pathName == '/' || pathName == '/index.html' || pathName == '/index.php') {
        filePath = path.join(root, './index.html');
        fs.readFile(filePath, (error, data) => {
            if (error) {
                // 404
                response.writeHead(404);
                response.end("Ops, page lost.");
            } else {
                response.writeHead(200);
                response.end(data)
            }
        })
    } else {
        fs.readFile(filePath, (error, data) => {
            if (error) {
                // 404
                response.writeHead(404);
                response.end("Ops, page lost.");
            } else {
                response.writeHead(200);
                response.end(data)
                // fs.createReadStream(filePath).pipe(response);
            }
        })
    }
});

httpServer.listen(httpPort, () => {
    console.log("http run at 'http://localhost:" + httpPort + "/'");
});
// * HTTP服务器 end ************************************************** //


// 服务器端口
const wsPort = 8081;

// 用户集合
// user格式：'token':{token:xxx,name:xxx},
let users = {};

// 房间列表集合
// room格式：'id': {id:'',title:'',user:[],start:false,ready:false,black:[],white:[],ate:[],countdown:10,turn:'0|1',offensive:'0|1'，count:0},
let rooms = {};

// * 服务器：接收总接口 start ************************************************** //
let server = ws.createServer(connect => {
    connect.on('text', (data) => {
        let str = JSON.parse(data);
        console.log(str);

        // 验证token
        let pass = Boolean(connect.token) && connect.token == str.data.token;

        switch (str.method) {
            case 'init':
                // 保存token，作为身份凭证, 唯一标识
                // {method:'init',  data:{token:xxx,name:'xxx'}}
                if (!str.data.token) {
                    str.data.token = createUserToken();
                    users[`${str.data.token}`] = {
                        token: str.data.token,
                        name: str.data.name
                    }
                } else {
                    // 携带token，同步更新上次连接数据
                }
                connect.token = str.data.token;
                connect.name = str.data.name;
                breadCast(connect, 'init');
                break;
            case 'rooms':
                // 获取房间列表
                // {method:'rooms',  data:{token:xxx}}
                if (pass) {
                    getRoomsList(connect)
                }
                break;
            case 'create':
                // 创建房间
                // {method:'create',  data:{token:xxx,title:xxx,password:'',countdown:10}}
                if (pass) {
                    createRoom(connect, str.data);
                }
                break;
            case 'enter':
                // 进入房间
                // {method:'enter',  data:{token:xxx, room:xxx}}
                if (pass) {
                    enterRoom(connect, str.data.room);
                }
                break;
            case 'ready':
                // 准备游戏
                // {method:'ready',  data:{token:xxx, room:xxx, ready:true}}
                if (pass && connect.room == str.data.room) {
                    readyRoom(connect, str.data.ready);
                }
                break;
            case 'move':
                // 下棋
                // {method:'move',  data:{token:xxx, room:xxx, chess:xxx}}
                if (pass && connect.room == str.data.room) {
                    moveChess(connect, str.data.chess)
                }
                break;
            case 'eat':
                // 吃棋
                // {method:'eat',  data:{token:xxx, room:xxx, chess:xxx}}
                if (pass && connect.room == str.data.room) {
                    eatChess(connect, str.data.chess)
                }
                break;
            case 'defeat':
                // 认输
                // {method:'defeat',  data:{token:xxx, room:xxx}}
                if (pass && connect.room == str.data.room) {
                    defeat(connect)
                }
                break;
            case 'peace-request':
                // 和棋请求
                // {method:'peace-request',  data:{token:xxx, room:xxx}}
                if (pass && connect.room == str.data.room) {
                    peaceRequest(connect)
                }
                break;
            case 'peace-feedback':
                // 和棋反馈
                // {method:'peace-feedback',  data:{token:xxx, room:xxx, feedback:false}}
                if (pass && connect.room == str.data.room) {
                    peaceFeedback(connect, r.data.feedback)
                }
                break;
            case 'out':
                // 离开房间
                // {method:'defeat',  data:{token:xxx, room:xxx}}
                if (pass) {
                    quiteRoom(connect, str.data.room)
                }
                break;
            case 'one':
                // 私聊
                // {method:'one',  data:{token:xxx,toToken:'xxx',msg:'xxx'}}
                if (pass) {
                    breadCast(connect, 'one', str.data.msg, str.data.toToken)
                    server.connections.forEach(item => {
                        if (item.token == str.data.toToken) {
                            item.sendText(JSON.stringify(str.data.msg));
                        }
                    })
                }
                break;
            case 'many':
                // 群聊
                // {method:'many',  data:{token:xxx,room:xxx,msg:'xxx'}}
                if (pass && connect.room == str.data.room) {
                    breadCast(connect, 'many', str.data.msg)
                }
                break;
            case 'all':
                // 世界广播
                // {method:'all',  data:{token:xxx,msg:'xxx'}}
                if (pass) {
                    breadCast(connect, 'all', str.data.msg)
                }
                break;
            default:
                connect.sendText('发的什么东西哟，看不懂');
        }
    })

    connect.on('close', () => {
        console.log("关闭");
    })

    connect.on('error', () => {
        console.log("请求异常");
    })
}).listen(wsPort, () => {
    console.log("websocket run at 'ws://localhost:" + wsPort + "/'")
})
// * 服务器：接收总接口 end ************************************************** //


// * 用户管理 start ************************************************** //
// 创建token
function createUserToken() {
    let token = setRandomStr(6);
    if (users.length > 0 && users.indexOf(token) > 0) {
        createUserToken()
        return
    }
    return token;
}

// 删除token
function delUserToken() {

}
// * 用户管理 end ************************************************** //


// * 房间相关方法 start ************************************************** //
// 获取房间列表
function getRoomsList(connect) {
    let list = [];
    for (let key in rooms) {
        let room = rooms[`${key}`];
        // let user = users[`${room.user[0]}`].name;
        let user = room.user[0].name
        let length = room.user.length;
        if (length >= 2 && !room.user[1]) {
            length = length - 1;
        }
        // 过滤信息
        let temp = {
            id: room.id,
            title: room.title,
            start: room.start,
            password: Boolean(room.password),
            total: length,
            user,
        };
        list.push(temp);
    }
    breadCast(connect, 'rooms', list);
}

// 创建房间
function createRoom(connect, data) {
    let roomid = setRandomStr(3);

    for (let key in rooms) {
        if (key == roomid) {
            createRoom(connect, data)
            return
        }
    }

    // 新建房间的模板(有待改进开发模式)
    rooms[`${roomid}`] = {
        id: roomid,
        title: data.title || 'default title',
        password: data.password || null,
        user: [],
        offensive: 0,
        ready: false,
        start: false,
        count: 0,
        countdown: data.countdown || 10,
        turn: 0,
        eat: false,
        black: [],
        white: [],
        ate: [],
    }
    enterRoom(connect, roomid);
}

// 进入房间：roomid
function enterRoom(connect, roomid) {

    let room = rooms[`${roomid}`];
    let user = {
        ...users[`${connect.token}`]
    };

    if (!room) {
        // 不存在 undefined
        breadCast(connect, 'error', '进入房间失败');
    } else {
        connect.room = roomid;
        if (room.user.length == 2 && !room.user[1]) {
            room.user[1] = user;
        } else {
            room.user.push(user);
        }

        // 广播 'enter'
        breadCast(connect, 'enter', room)
    }

}

// 离开房间
function quiteRoom(connect, roomid) {
    let room = rooms[`${roomid}`];

    if (!room) {
        // 不存在 undefined
        breadCast(connect, 'error', '操作错误');
    } else {
        if (room.user[0] && connect.token == room.user[0].token) {
            // 房主
            if (room.user.length == 1) {
                // 空房间，删除
                delete rooms[`${roomid}`];
                breadCast(connect, 'tip-self', "离开房间");
                return
            } else if (room.user.length == 2) {
                if (!room.user[1]) {
                    // 空房间，删除
                    delete rooms[`${roomid}`];
                    breadCast(connect, 'tip-self', "离开房间");
                    return
                } else {
                    if (room.start) {
                        // 投降
                        defeat(connect);
                    } else {
                        room.ready = false;
                        breadCast(connect, 'tip-to-room', `${'房主'+connect.name + '，离开房间'}`);
                    }
                    room.user[0] = {
                        ...room.user[1]
                    };
                    room.user.splice(1, 1);
                }
            } else {
                if (room.start) {
                    // 投降
                    defeat(connect);
                } else {
                    room.ready = false;
                    breadCast(connect, 'tip-to-room', `${'房主'+connect.name + '，离开房间'}`);
                }
                if (room.user[1]) {
                    room.user[0] = {
                        ...room.user[1]
                    };
                    room.user[1] = null;
                } else {
                    room.user[0] = {
                        ...room.user[2]
                    };
                    room.user.splice(2, 1);
                }
            }
            // 换房主的提示
            breadCast(connect, 'tip-to-one', "成为房主", room.user[0].token);
            // 房主或玩家离开房间，才会发送更新的房间，观战者退出房间不需要发送更新
            // 待完善：暂时不用‘上位’成为对手
            if (!room.user[1]) {
                room.user.splice(1, 1);
            }

            breadCast(connect, 'out', room);

        } else if (room.user[1] && connect.token == room.user[1].token) {
            // 对手
            if (room.start) {
                // 投降
                defeat(connect);
            } else {
                room.ready = false;
                breadCast(connect, 'tip-to-room', `${connect.name + '，离开房间'}`);
            }
            room.user[1] = null;
            // 房主或玩家离开房间，才会发送更新的房间，观战者退出房间不需要发送更新
            // 待完善：暂时不用‘上位’成为对手
            if (!room.user[1]) {
                room.user.splice(1, 1);
            }
            breadCast(connect, 'out', room);
        } else {
            // 观战者
            room.user.forEach((item, index) => {
                if (item.token == connect.token) {
                    room.user.splice(index, 1);
                }
            })
            breadCast(connect, 'tip-self', "离开房间");
        }
        connect.room = null;
    }
}

// 准备、开始
function readyRoom(connect, isReady) {
    let room = rooms[`${connect.room}`];
    if (!room) {
        // undefined
    } else {
        if (room.user[0] && room.user[1]) {
            // 有对手，才能准备
            if (room.user[1].token == connect.token) {
                // 非房主 => 准备
                if (room.start == false) {
                    room.ready = isReady || !room.ready;
                    // 广播 'ready'
                    breadCast(connect, 'ready', room);
                    if (room.ready) {
                        breadCast(connect, 'tip-self', '已准备');
                    } else {
                        breadCast(connect, 'tip-self', '取消准备');
                    }
                } else {
                    breadCast(connect, 'tip-self', '游戏已开始');
                }
            } else if (room.user[0].token == connect.token) {
                // 房主 => 开始
                if (room.ready == true) {
                    room.start = true;

                    // 第一回合开始：轮到先手下棋
                    room.count = 1;
                    room.turn = room.offensive;

                    // 广播 'start'
                    breadCast(connect, 'tip-to-room', '游戏开始！');
                    breadCast(connect, 'start', room);
                } else {
                    breadCast(connect, 'tip-self', '对手未准备');
                }
            } else {
                breadCast(connect, 'tip-self', '观战状态');
            }
        } else {
            breadCast(connect, 'tip-self', '等待玩家加入');
        }
    }
}

// 认输
function defeat(connect) {
    let room = rooms[`${connect.room}`];
    if (!room) {
        // room undefined
    } else {
        // 游戏开始 才能投降
        if (!room.start || !room.user[0] || !room.user[1]) return
        // 权限
        if (connect.token == room.user[0].token || connect.token == room.user[1].token) {
            let winerToken;
            if (connect.token == room.user[0].token) {
                // winerToken = users[`${room.user[1]}`].token;
                winerToken = room.user[1].token;
            } else {
                winerToken = room.user[0].token;
                // winerToken = users[`${room.user[0]}`].token;
            }
            resetGame(room);
            breadCast(connect, 'defeat', room, winerToken);
        }
    }
}

function peaceRequest(connect) {
    let room = rooms[`${connect.room}`];
    if (!room) {
        // undefined
        breadCast(connect, 'error', '系统错误：房间号不存在');
    } else {
        // 当前下棋者才能发起和棋
        if (room.user[room.turn] && connect.token == room.user[room.turn].token) {
            if (room.turn == 0) {
                breadCast(connect, 'peace-request', '发起和棋请求', room.user[1].token);
            } else {
                breadCast(connect, 'peace-request', '发起和棋请求', room.user[0].token);
            }
        }
    }
}

function peaceFeedback(connect, fb) {
    let room = rooms[`${connect.room}`];
    if (!room) {
        // undefined
        breadCast(connect, 'error', '系统错误：房间号不存在');
    } else {
        if (fb) {
            // 同意和棋
            breadCast(connect, 'peace');
            // resetGame(room)
        } else {
            // 不同意
            breadCast(connect, 'tip-to-room', `${connect.name + '不同意和棋'}`);
        }
    }
}

// 重置游戏
function resetGame(room) {
    room.start = false;
    room.ready = false;
    room.count = 0;
    if (room.offensive == 0) {
        room.offensive = 1;
    } else {
        room.offensive = 0;
    }
    room.turn = room.offensive;
    room.black = [];
    room.white = [];
    room.eat = false;
    room.ate = [];
}

// 踢人

// 上位

// * 房间 end ************************************************** //

// * 移动棋子 start ************************************************** //
function moveChess(connect, chess) {
    let room = rooms[`${connect.room}`];
    if (!room) {
        // undefined
        breadCast(connect, 'error', '系统错误：房间号不存在');
    } else {
        // 吃棋阶段，限流
        if (room.eat || !room.user[room.turn]) return
        // 权限:轮到玩家下棋
        if (connect.token == room.user[room.turn].token) {
            // 确定棋子颜色:先手黑棋后手白棋
            if (room.turn == room.offensive) {
                ruleMove(connect, room, "black", chess);
            } else {
                ruleMove(connect, room, "white", chess);
            }
        }
    }
}

// 棋子操作的规则
function ruleMove(connect, room, color, chess) {
    if (room.count <= 9) {
        // 下棋
        if (!(room.black.includes(chess)) && !(room.white.includes(chess)) && !(room.ate.includes(chess))) {
            room[`${color}`].push(chess);
            hasMoved(connect, room, color, chess);
        }
    } else {
        // 走棋(飞棋)阶段
        let f = chess.substr(0, 2);
        let t = chess.substr(2, 2);
        let i = room[`${color}`].indexOf(f);
        if (room[`${color}`].includes(f) && !(room.black.includes(t)) && !(room.white.includes(t))) {
            if (room[`${color}`].length <= 3) {
                // 飞棋
                room[`${color}`].splice(i, 1, t);
                hasMoved(connect, room, color, t);
            } else {
                // 走棋
                if (checkMove(f, t)) {
                    room[`${color}`].splice(i, 1, t);
                    hasMoved(connect, room, color, t);
                }
            }
        }
    }
}

// 棋子操作后的反馈
function hasMoved(connect, room, color, chess) {
    // 对手是否可走棋：对方不可移动 => 对方输
    if (room.count > 9) {
        let opponentCanMove = hasMovedOpponentCanMove(room, color);
        if (!opponentCanMove) {
            resetGame(room);
            breadCast(connect, 'winner', room, connect.token);
            return
        }
    }

    let opponentChessColor = 'white';
    if (color == 'white') {
        opponentChessColor = 'black';
    }
    // 是否成三：  吃棋  或  对方下棋
    if (checkEat(room, color, chess)) {
        if (checkAllThree(room, opponentChessColor)) {
            // 状态：对方都是成三，无棋可吃，跳过吃棋阶段，对方下棋
            increaseCount(room);
            breadCast(connect, 'tip-self', '成三，无子可吃');
        } else {
            // 成三，提示语
            room.eat = true;
            breadCast(connect, 'tip-self', '成三，吃棋');
        }
    } else {
        // 对手token
        let opponentToken = room.user[1].token;
        if (room.turn == 1) {
            opponentToken = room.user[0].token;
        }

        // 状态：对方下棋
        increaseCount(room);
        breadCast(connect, 'tip-to-one', '轮到您', opponentToken);
    }

    // 手棋下完后，不可下棋点清空
    if (room.count == 10) {
        room.ate = [];
    }

    // 广播 ‘move’
    breadCast(connect, 'move', room);
}

function hasMovedOpponentCanMove(room, color) {
    let opponentChessArr = [];
    let result = false;
    if (color == 'white') {
        if (room.black.length <= 3) {
            result = true;
        }
        opponentChessArr = room.black;
    } else {
        if (room.white.length <= 3) {
            result = true;
        }
        opponentChessArr = room.white;
    }
    let strChessNum = '8123456781';
    let chessArr = [...room.white, ...room.black];

    opponentChessArr.forEach(item => {
        let capt = item.substr(0, 1);
        let num = Number(item.substr(1, 1));
        if (!chessArr.includes(capt + strChessNum[num + 1]) ||
            !chessArr.includes(capt + strChessNum[num - 1])) {
            result = true;
        }
        if (/^[2468]{1}$/.test(num)) {
            if ((capt == 'a' || capt == 'c') &&
                !chessArr.includes('b' + num)) {
                result = true;
            }
            if (capt == 'b' && (!chessArr.includes('a' + num) || !chessArr.includes('c' + num))) {
                result = true;
            }
        }
    })

    return result
}

// 走棋阶段：是否可以落棋
function checkMove(start, end) {

    let startCapt = start.substr(0, 1);
    let endCapt = end.substr(0, 1);
    let startNum = Number(start.substr(1, 1));
    let endNum = Number(end.substr(1, 1));

    if (startCapt == endCapt) {
        let numStr = '8123456781';
        if (numStr[startNum - 1] == endNum || numStr[startNum + 1] == endNum) {
            return true
        }
    }

    if (startNum == endNum && (/^[2468]{1}$/.test(startNum))) {
        if (startCapt == 'b' || endCapt == 'b') {
            return true
        }
    }

    // 不能移动
    return false
}
// * 移动棋子 end ************************************************** //


// * 吃掉棋子 start ************************************************** //
function eatChess(connect, chess) {
    let room = rooms[`${connect.room}`];
    if (!room) {
        // 房间不存在
        breadCast(connect, 'error', '操作错误');
        return
    } else {
        // 吃棋阶段：限流
        if (!room.eat || !room.user[room.turn]) return

        // 校验吃棋玩家
        if (connect.token == room.user[room.turn].token) {
            // 确定棋子颜色：先手黑棋吃白棋，后手白棋吃黑棋
            if (room.turn == room.offensive) {
                eating(connect, room, "white", chess);
            } else {
                eating(connect, room, "black", chess);
            }
        }
    }
}

function eating(connect, room, color, chess) {
    let i = room[`${color}`].indexOf(chess);
    // 吃掉对方棋子， 且不是成三的
    if (i >= 0 && !checkEat(room, color, chess)) {
        // 吃棋
        room[`${color}`].splice(i, 1);
        room.eat = false;
        // 被吃，不可下棋区域
        if (room.count <= 9) {
            room.ate.push(chess);
        } else {
            room.ate = [];
        }
        // 对手TOKEN
        let opponentToken = room.user[1].token;
        if (room.turn == 1) {
            opponentToken = room.user[0].token;
        }
        // 吃掉之后，走棋阶段对手少于三个棋子，胜利
        if (room.count > 9 && room[`${color}`].length < 3) {
            resetGame(room);
            breadCast(connect, 'winner', room, opponentToken);
        } else {
            // 轮到对手下棋
            increaseCount(room);
            // 广播 'eat'
            breadCast(connect, 'tip-to-one', '轮到您', opponentToken);
            breadCast(connect, 'eat', room);
        }
    }
}
// * 吃掉棋子 end ************************************************** //


// * 其他函数 start ************************************************** //
// 随机字符串
function setRandomStr(num) {
    let tmp = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789';
    let result = '';
    for (let i = 0; i < num; i++) {
        let index = Math.floor(Math.random() * tmp.length);
        result += tmp.substr(index, 1);
    }
    return result
}

// 回合自增count，轮流下棋换手turn
function increaseCount(room) {
    // 后手 => 下棋成功后 => 回合+1
    if (room.turn != room.offensive && !room.eat) {
        room.count++;
    }
    // !turn 对方下棋
    if (room.turn == 0) {
        room.turn = 1;
    } else {
        room.turn = 0;
    }
}

// 棋子是否成三
function checkEat(room, color, chess) {
    let ruleEatMap = [
        ['a1', 'a2', 'a3'],
        ['a3', 'a4', 'a5'],
        ['a5', 'a6', 'a7'],
        ['a7', 'a8', 'a1'],
        ['b1', 'b2', 'b3'],
        ['b3', 'b4', 'b5'],
        ['b5', 'b6', 'b7'],
        ['b7', 'b8', 'b1'],
        ['c1', 'c2', 'c3'],
        ['c3', 'c4', 'c5'],
        ['c5', 'c6', 'c7'],
        ['c7', 'c8', 'c1'],
        ['a2', 'b2', 'c2'],
        ['a4', 'b4', 'c4'],
        ['a6', 'b6', 'c6'],
        ['a8', 'b8', 'c8']
    ];
    let result = false;
    ruleEatMap.forEach(map => {
        if (map.indexOf(chess) >= 0) {
            if (room[`${color}`].includes(map[0]) && room[`${color}`].includes(map[1]) && room[`${color}`].includes(map[2])) {
                result = true;
            }
        }
    })
    return result;
}

// 所有棋子已成三
function checkAllThree(room, color) {
    let chessArr = room[`${color}`];
    let result = true;
    chessArr.forEach(item => {
        if (!checkEat(room, color, item)) {
            result = false;
        }
    })
    return result;
}

// * 其他函数 end ************************************************** //

// * 服务器：广播总接口 start ************************************************** //
function breadCast(connect, method, data, id) {
    switch (method) {
        case 'init':
            let tempInit = {
                method: 'init',
                data: {
                    token: connect.token,
                    name: connect.name
                }
            }
            connect.sendText(JSON.stringify(tempInit))
            break;
        case 'rooms':
            // 获取房间列表
            connect.sendText(JSON.stringify({
                method,
                data
            }));
            break;
        case 'enter':
        case 'ready':
        case 'start':
        case 'move':
        case 'eat':
            // 房间全体广播
            server.connections.forEach(item => {
                if (item.room == connect.room) {
                    let temp = {
                        method,
                        data
                    }
                    item.sendText(JSON.stringify(temp));
                }
            })
            break;
        case 'defeat':
            server.connections.forEach(item => {
                if (item.room == connect.room) {
                    let temp;
                    let winnerName = users[`${id}`].name;

                    if (item.token == connect.token) {
                        // 失败者
                        temp = {
                            method: 'tip',
                            data: '投降，失败'
                        }
                        item.sendText(JSON.stringify(temp));
                    } else if (item.token == id) {
                        // 胜利者
                        temp = {
                            method: 'tip',
                            data: '对手投降, 获胜'
                        }
                        item.sendText(JSON.stringify(temp));
                    } else {
                        // 旁观者
                        temp = {
                            method: 'tip',
                            data: `${'对手投降, ' + winnerName + ' ,胜利' }`
                        }
                        item.sendText(JSON.stringify(temp));
                    }
                    temp = {
                        method,
                        data
                    }
                    item.sendText(JSON.stringify(temp));
                }
            })
            break;
        case 'winner':
            server.connections.forEach(item => {
                if (item.room == connect.room) {
                    let temp;
                    if (item.token == connect.token) {
                        // 胜利者
                        temp = {
                            method: 'tip',
                            data: '获胜'
                        }
                        item.sendText(JSON.stringify(temp));
                    } else if (item.token == id) {
                        // 失败者
                        temp = {
                            method: 'tip',
                            data: '失败'
                        }
                        item.sendText(JSON.stringify(temp));
                    } else {
                        // 旁观者
                        temp = {
                            method: 'tip',
                            data: `${connect.name + ' ,胜利' }`
                        }
                        item.sendText(JSON.stringify(temp));
                    }
                    temp = {
                        method,
                        data
                    }
                    item.sendText(JSON.stringify(temp));
                }
            })
            break;
        case 'out':
            // 房间其他人
            server.connections.forEach(item => {
                if (item.room == data.id) {
                    if (item.token != connect.token) {
                        let temp = {
                            method,
                            data
                        }
                        item.sendText(JSON.stringify(temp));
                    }
                }
            })
            break;
        case 'tip-self':
            // 自己：提示语
            let tempTips = {
                method: 'tip',
                data
            }
            connect.sendText(JSON.stringify(tempTips));
            break;
        case 'tip-to-room':
            server.connections.forEach(item => {
                if (item.room == connect.room) {
                    let temp = {
                        method: 'tip',
                        data
                    }
                    item.sendText(JSON.stringify(temp));
                }
            })
            break;
        case 'tip-to-one':
            server.connections.forEach(item => {
                if (item.token == id) {
                    let temp = {
                        method: 'tip',
                        data
                    }
                    item.sendText(JSON.stringify(temp));
                }
            })
            break;
        case 'peace':
            server.connections.forEach(item => {
                if (item.room == connect.room) {
                    let temp = {
                        method: 'peace',
                        data: '和棋'
                    }
                    item.sendText(JSON.stringify(temp));
                }
            })
            break;
        case 'peace-request':
            server.connections.forEach(item => {
                if (item.room == connect.room) {
                    let temp;
                    if (item.token == connect.token) {
                        // 发起者
                        temp = {
                            method: 'tip',
                            data: '和棋请求已发送'
                        }
                        // item.sendText(JSON.stringify(temp));
                    } else if (item.token == id) {
                        // 接收请求者
                        temp = {
                            method: 'confirm',
                            data: `${connect.name + '发起和棋，是否同意？' }`
                        }
                        // item.sendText(JSON.stringify(temp));
                    } else {
                        // 旁观者
                        temp = {
                            method: 'tip',
                            data: `${connect.name + '发起和棋' }`
                        }
                    }
                    item.sendText(JSON.stringify(temp));
                }
            })
            break;

        case 'peace-feedback':
            server.connections.forEach(item => {
                if (item.room == connect.room) {
                    let temp;
                    if (item.token == connect.token) {
                        // 发起者
                        temp = {
                            method: 'tip',
                            data: '和棋请求已发送'
                        }
                        // item.sendText(JSON.stringify(temp));
                    } else if (item.token == id) {
                        // 接收请求者
                        temp = {
                            method: 'confirm',
                            data: `${connect.name + '发起和棋，是否同意？' }`
                        }
                        // item.sendText(JSON.stringify(temp));
                    } else {
                        // 旁观者
                        temp = {
                            method: 'tip',
                            data: `${connect.name + '发起和棋' }`
                        }
                    }
                    item.sendText(JSON.stringify(temp));
                }
            })
            break;
        case 'system-one':

            //  个人：系统信息
            break;
        case 'system-many':
            //  房间：系统信息
            break;
        case 'system-all':
            //  世界：系统信息
            break;
        case 'one':
            //  单独聊天
            server.connections.forEach(item => {
                if (item.token == id) {
                    let temp = {
                        method,
                        data,
                        fromToken: connect.token,
                        from: connect.name,
                        create: Date.now()
                    }
                    item.sendText(JSON.stringify(temp));
                }
            })
            break;
        case 'many':
            //  房间聊天
            let tempMany = {
                method,
                data,
                fromToken: connect.token,
                from: connect.name,
                create: Date.now()
            }
            server.connections.forEach(item => {
                if (item.room == connect.room) {
                    item.sendText(JSON.stringify(tempMany));
                }
            })
            break;
        case 'all':
            // 世界聊天
            let tempAll = {
                method,
                data,
                fromToken: connect.token,
                from: connect.name,
                create: Date.now()
            }
            server.connections.forEach(item => {
                item.sendText(JSON.stringify(tempAll));
            })
            break;

        default:
            server.connections.forEach(item => {
                if (item.room == connect.room) {
                    let temp = {
                        method: 'error',
                        data: 'error',
                        create: Date.now()
                    }
                    item.sendText(JSON.stringify(temp));
                }
            })
    }
}
// * 服务器：广播总接口 end ************************************************** //